﻿<%@ WebHandler Language="C#" Class="WorkflowstepWorkTimeQueryReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 件号工时数据查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.5.16
 **/

public class WorkflowstepWorkTimeQueryReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getQuerySql(JObject jObject)
    {
        string sql = @"
SELECT pb.productname,
       p.productrevision,
       wfb.workflowname,
       wf.workflowrevision,
       ws.sequence,
       s.specno,
       s.opdesc,
       ws.makeempcounts,
       w.workcentername,
       t.teamname,
       ws.preparecycle,ws.makecycle,ws.transfercycle,ws.shipcycle,ws.commicycle,
       rd.resourcename,ws.chargingqty,ct2.lastchangedate,
       CASE WHEN s.controlcode = 'LY05' THEN '固定外委'
            WHEN s.factoryid <> wf.factoryid THEN '固定转工'
            ELSE '普通序' 
       END spectype
FROM product p
LEFT JOIN productbase pb ON p.productbaseid = pb.productbaseid
LEFT JOIN workflowbase wfb1 ON wfb1.workflowbaseid = p.workflowbaseid
LEFT JOIN workflow wf ON wf.workflowid = nvl(wfb1.revofrcdid, p.workflowid)
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
LEFT JOIN factory f ON f.factoryid = wf.factoryid
LEFT JOIN Workflowstep ws ON ws.workflowid = wf.workflowid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN specresourceinfo sc ON sc.specid = s.specid
LEFT JOIN Resourcedef rd ON rd.resourceid = sc.resourceid
LEFT JOIN workcenter w ON w.workcenterid = ws.workcenterid
LEFT JOIN team t ON t.teamid = ws.teamid
LEFT JOIN Changestatus ct ON ct.parentid = p.productid
LEFT JOIN Changestatus ct2 ON ct2.parentid = wf.workflowid
";
        if (jObject["selecttype"] != null)
        {
            if (jObject["selecttype"].ToString() == "最新工艺")
            {
                sql += @"
LEFT JOIN (
     SELECT pb.productname,MAX(ct.lastchangedate) lastchangedate
     FROM product p
     LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
     LEFT JOIN Changestatus ct ON ct.parentid = p.productid
     WHERE p.workflowid IS NOT NULL
     GROUP BY pb.productname
) t ON t.productname = pb.productname
WHERE t.lastchangedate = ct.lastchangedate
";
            }
            else
            {
                sql += " WHERE pb.revofrcdid = p.productid ";
            }
        }

        // 分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryid = '{0}' ", jObject["factoryid"].ToString());
        }

        // 件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND pb.productname = '{0}' ", jObject["productname"].ToString());
        }

        //工艺创建时间
        if (jObject["createdate"] != null && jObject["createdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["createdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND ct.lastchangedate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND ct.lastchangedate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }
        sql += @"
ORDER BY pb.productname,ws.sequence
";
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        dt.Columns["productname"].Caption = "零件图号";
        dt.Columns["productrevision"].Caption = "零件版本";
        dt.Columns["workflowname"].Caption = "工艺名称";
        dt.Columns["workflowrevision"].Caption = "工艺版本";
        dt.Columns["specno"].Caption = "工序号";
        dt.Columns["opdesc"].Caption = "工序名称";
        dt.Columns["makeempcounts"].Caption = "作业人数";
        dt.Columns["workcentername"].Caption = "工区";
        dt.Columns["teamname"].Caption = "班组";
        dt.Columns["preparecycle"].Caption = "准备工时";
        dt.Columns["makecycle"].Caption = "加工工时";
        dt.Columns["transfercycle"].Caption = "转运工时";
        dt.Columns["shipcycle"].Caption = "转工周期";
        dt.Columns["commicycle"].Caption = "外委周期";
        dt.Columns["resourcename"].Caption = "设备";
        dt.Columns["chargingqty"].Caption = "装炉/槽量";
        dt.Columns["lastchangedate"].Caption = "工艺创建时间";
        dt.Columns.Remove("sequence");
        dt.Columns["spectype"].Caption = "工序类型";
        ExportHelper.ExportExcel(dt, "件号工时数据查询报表");
    }
}